package com.ksl.kinglockguard.utils;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.util.LongSparseArray;

import com.lsk.open.core.MyLog;

@SuppressWarnings("unchecked")
public class AnalyizeDrawabletool {

	static int deleteNum = 0;
	
	@SuppressLint("NewApi")
	synchronized public static void clearAppDrawableCache(Context context) {
		try {
			// MyLog.v("ydy",
			// context.getClass().getName()+"     clearAppDrawableCache ");
			context.getApplicationContext().getResources().flushLayoutCache();
			// clearPreloadDrawable(context);
			Field fd = context.getApplicationContext().getResources()
					.getClass().getDeclaredField("mDrawableCache");
			fd.setAccessible(true);
			
			final LongSparseArray<WeakReference<Object>> array2 = (LongSparseArray<WeakReference<Object>>) fd
					.get(context.getApplicationContext().getResources());
			// MyLog.i("ydy", "clearAppDrawableCache array2.size==" +
			// array2.size());
			fd.set(context.getApplicationContext().getResources(),
					new LongSparseArray<WeakReference<Object>>());
			final List<WeakReference<Object>> arrayTmp = new ArrayList<WeakReference<Object>>();
			// final List<Long> arrayKey = new ArrayList<Long>();
			for (int i = 0; i < array2.size(); i++) {
				arrayTmp.add(array2.valueAt(i));

				// arrayKey.add(key);
			}
			array2.clear();
			// arrayTmp.clear();
			// for(int i=0;i<arrayKey.size();i++){
			// array2.remove(arrayKey.get(i));
			// }

			new Thread() {

				@Override
				public void run() {
					synchronized (AnalyizeDrawabletool.class) {
						try {
							deleteNum = 0;
							// MyLog.v("ydys",
							// "clearAppDrawableCache markStringDeque.size()=="
							// +
							for (int i = 0; i < arrayTmp.size(); i++) {
								processObject(arrayTmp.get(i).get(), i, false,
										true);

							}
							arrayTmp.clear();
						} catch (Exception e) {
							e.printStackTrace();
						}

					}

				}

			}.start();

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static long processObject  (Object aObj, int id, boolean save, boolean clean) {
		int size = 0;
		try {
			Object obj = aObj;
			if (obj == null)
				return size;
			String name = obj.getClass().getName();
			if (name.contains("BitmapState")) {
				Field fd = Class.forName(
						"android.graphics.drawable.BitmapDrawable$BitmapState")
						.getDeclaredField("mBitmap");
				fd.setAccessible(true);
				Bitmap bmp = (Bitmap) fd.get(obj);
				if (bmp != null) {
					int w = bmp.getWidth();
					int h = bmp.getHeight();
					/*
					 * size = w * h * 4; MyLog.v("ydys", "size: " + "w=" + w +
					 * ", h=" + h + ",mem=" + w * h * 4 + "字节");
					 */

					// clean = false;
					// save=true;

					// }
					
					save=true;//todo ydy
					if (save && !bmp.isRecycled()) {
						File folder = new File("/sdcard/tyu_bmp/");
						if (!folder.exists()) {
							folder.mkdir();
						}
						String filename = "/sdcard/tyu_bmp/" + w + "X" + h
								+ "_" + bmp.toString();

						try {
							File myCaptureFile = new File(filename + ".png");
							BufferedOutputStream bos = new BufferedOutputStream(
									new FileOutputStream(myCaptureFile));

							bmp.compress(Bitmap.CompressFormat.PNG, 80, bos);
							MyLog.i("ydy2", "processObject  **save** name  "
									+ bmp.toString() + "w==  " + w + " h== "
									+ h);
							bos.flush();
							bos.close();
						} catch (Exception e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}

					// 大于100kb,就回收
					// if (clean && isMatch(bmp.toString()))
			/*		int edge = 100 * 1024;
					if (clean) {
						size = w * h * 4;
						if (size > edge) {
							bmp.recycle();
							deleteNum++;
							bmp = null;
							fd.set(obj, null);
							fd = null;
						}

					}*/

				}

			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return size;

	}
	
	public static void  saveBitmap(final Bitmap bmp,final boolean isSave){
		new Thread(new Runnable(){

			@Override
			public void run() {
				if (isSave && !bmp.isRecycled()) {
					int w = bmp.getWidth();
					int h = bmp.getHeight();
					
					File folder = new File("/sdcard/tyu_bmp/");
					if (!folder.exists()) {
						folder.mkdir();
					}
					String filename = "/sdcard/tyu_bmp/" + w + "X" + h
							+ "_" + bmp.toString();

					try {
						File myCaptureFile = new File(filename + ".png");
						BufferedOutputStream bos = new BufferedOutputStream(
								new FileOutputStream(myCaptureFile));

						bmp.compress(Bitmap.CompressFormat.PNG, 80, bos);
						MyLog.i("ydy2", "processObject  **save** name  "
								+ bmp.toString() + "w==  " + w + " h== "
								+ h);
						bos.flush();
						bos.close();
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				
			}
			
		}).start();
		
	}
}
